/*
 * @Date: 2025-02-02 22:26:09
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-02-13 10:04:10
 * @FilePath: /vue3-admin/src/service/useMy.ts
 */

import {
    readMyInfo,
    PasswordParam,
    updateMyPassword as updateMyPasswordApi
} from '@/api/my';
import { useUserStore } from '@/store';
import type { MyInfo } from '@/typings/api/my';
import { message } from '@/utils';

export { PasswordParam };

export const useMy = () => {
    const userStore = useUserStore();

    const info = ref<MyInfo>();
    const infoLoading = ref(false);

    const getMyInfo = () => {
        if (infoLoading.value) return;
        infoLoading.value = true;
        return readMyInfo()
            .then((res) => {
                info.value = res.data;
                return res;
            })
            .finally(() => {
                infoLoading.value = false;
            });
    };

    const updatepasswordLoading = ref(false);
    const updateMyPassword = (param: PasswordParam) => {
        if (updatepasswordLoading.value) return;
        updatepasswordLoading.value = true;
        return updateMyPasswordApi(param).finally(() => {
            updatepasswordLoading.value = false;
        });
    };

    const updateUserStoreMyInfo = async () => {
        try {
            await getMyInfo();
            if (info.value) {
                userStore.setMyInfo(info.value);
            }
            return Promise.resolve();
        } catch (e) {
            console.log(e);
        }
    };

    return {
        info,
        infoLoading,
        getMyInfo,
        updatepasswordLoading,
        updateMyPassword,
        updateUserStoreMyInfo
    };
};
